
package com.zcp.pcsuitall;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

public class PhoneServiceAllActivity extends Activity implements ActivityInterface {
    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        usbConnection = getString(R.string.usb_coning);
        unUsbConnection = getString(R.string.please_usb_con);
        context = this;

        // 注册监听广播服务
        IntentReceiver.register(this);
        if (this.getIntent() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                port = bundle.getInt("port", port);
                key = bundle.getString("name");
            }
            Log.i(TAG, "StartActivity port=" + port + "name=" + key);
        }
        stopService();// 由create启动的，通通把服务关闭一次，由于有状态小图标，在启动过程中如果按home按键是在stop-start之间调用，就会启动和关闭小图标.
        Log.e(TAG, "StartActivity create");
        mIntentFilter.addAction(Intent.ACTION_UMS_DISCONNECTED);
        registerReceiver(connectionStatusReceiver, mIntentFilter);

        initializeButton();

    }

    private void initializeButton() {
        usbStatusTitle = (TextView) findViewById(R.id.TextViewUsbStatus);
        Button button = (Button) findViewById(R.id.button_wifi);

        Button hotButton = (Button) findViewById(R.id.button_hotspot);

        // 当系统版本小于2.2时候就屏蔽热点链接按钮，2.2以下没有这个功能。
        if (android.os.Build.VERSION.SDK_INT < 8) {
            hotButton.setVisibility(View.INVISIBLE);
        }

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                stopService();
                Intent intent=new Intent(context,WifiActivity.class);
                startActivity(intent);
                finish();
            }
        });

        hotButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                stopService();
                Intent intent=new Intent(context,HotActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        Log.i("222", "onActivityResult=" + requestCode);
//        if (requestCode == openSocketByWifi) {
//            restartServiceByWifi();
//        } else if (requestCode == openSocketByHot) {
//            restartServiceByWifiAp();
//        }
//
//    }

    @Override
    protected void onStart() {
        super.onStart();
        startService();
        Log.e(TAG, "StartActivity start");
    }

    @Override
    protected void onStop() {
        Log.e(TAG, "StartActivity stop");
        stop();
    }

    @Override
    protected void onDestroy() {
        if (connectionStatusReceiver != null) {
            unregisterReceiver(connectionStatusReceiver);
        }
        IntentReceiver.unRegister(this);
        super.onDestroy();
    }

    private void stop() {
        super.onStop();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            checkExist();
        }
        return true;
    }

//    /**
//     * 通过wifi的ip重启服务
//     */
//    private void restartServiceByWifiAp() {
//
//        Log.i("222", "restartServiceByWifiAp");
//        if (SuitUtil.getWifiApEnable(context)) {
//            ip = SuitUtil.getLocalIpAddress();
//            Log.e("222", "restartServiceByWifiAp=" + ip);
//            stopService();
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//            startService();
//        }
//    }

//    /**
//     * 通过wifi的ip重启服务
//     */
//    private void restartServiceByWifi() {
//        Log.e("222", "restartServiceByWifi");
//        if (SuitUtil.isWifiEnable(context)) {
//            ip = SuitUtil.getLocalIpAddress();
//            Log.e("222", "restartServiceByWifi=" + ip);
//            stopService();
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//            startService();
//        }
//    }

    /**
     * 退出前检查一下。
     * 
     * @return
     */
    private void checkExist() {
        AlertDialog.Builder builder = new Builder(this);
        builder.setMessage(this.getString(R.string.exist));
        builder.setTitle(this.getString(R.string.Confirm));
        builder.setPositiveButton(this.getString(R.string.ok),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        stopService();
                        finish();
                    }
                });

        builder.setNegativeButton(this.getString(R.string.cancel),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create().show();
    }

    /**
     * 启动socket服务连接。<br>
     * 
     * @param context
     */
    private void startService() {

        SharedPreferences shPre = getSharedPreferences("PcSuitPhone", Context.MODE_PRIVATE);
        if (shPre.getString("haveStartSocket", "notSet").equals("ok")) {
            return;
        }
        Intent startIntent = new Intent(this, SocketService.class);
        Bundle startBundle = new Bundle();

        startBundle.putInt("server_port", port);// 默认socket端口
        startBundle.putString("ip", ip);
        startBundle.putString("cipherKey", cipherKey);
        startBundle.putString("class","PhoneServiceAllActivity");
        startIntent.putExtras(startBundle);
        startService(startIntent);

        Editor editor = shPre.edit();
        editor.putString("haveStartSocket", "ok");
        editor.commit();

        Log.i(TAG, "onReceive startService " + port);

    }

    /**
     * 停止socket服务。
     * 
     * @param context
     */
    private void stopService() {
        try {
            Intent stopIntent = new Intent(this, SocketService.class);
            stopService(stopIntent);

            SharedPreferences shPre = getSharedPreferences("PcSuitPhone", Context.MODE_PRIVATE);
            Editor editor = shPre.edit();
            editor.putString("haveStartSocket", "not");
            editor.commit();
            // cancelNotifyIcon();
            Log.i(TAG, "onReceive stopService");
        } catch (Exception e) {
            Log.e(TAG, "stopService error" + e.getMessage());
        }
    }

    private void setConnectionStatus(boolean isConnection) {
        if (usbStatusTitle != null) {
            if (isConnection) {
                usbStatusTitle.setText(usbConnection);
                usbStatusTitle.setTextColor(getResources().getColor(R.color.green));
            } else {
                usbStatusTitle.setText(unUsbConnection);
                usbStatusTitle.setTextColor(getResources().getColor(R.color.black));
            }
        }
    }

    private String cipherKey="asdfghjk";
    private IntentFilter mIntentFilter = new IntentFilter(CONNECTION_STATUS);

    private String ip = "127.0.0.1";

    private int port = 8849;

    private String key = null;// 启动的时候设置一个key

    private static final String TAG = "PhoneServiceAllActivity";

    private Activity context = null;

//    private int openSocketByWifi = 1001;
//
//    private int openSocketByHot = 1002;

    private String usbConnection;// USB连接使用中...

    private String unUsbConnection;// 请把手机通过USB连接电脑

    private TextView usbStatusTitle = null;

    @Override
    public void stopActivity(String stopKey) {
        if (("all".equals(stopKey) || (stopKey != null && stopKey.equals(key)))) {
            stopService();
            this.finish();
        }
    }

    private final BroadcastReceiver connectionStatusReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
//            Log.i("222", "connectionStatusReceiver===" + intent.getAction());
            // android.intent.action.USB_DISCONNECTED
            if (intent != null) {
                if (CONNECTION_STATUS.equals(intent.getAction())) {
                    boolean isconnection = intent.getBooleanExtra(CONNECTION_STATUS_KEY, false);
                    setConnectionStatus(isconnection);
                } else if (Intent.ACTION_UMS_DISCONNECTED.equals(intent.getAction())) {
                    setConnectionStatus(false);
                }
            }

        }
    };

    public static final String CONNECTION_STATUS = "pc_suit_connection_status";

    public static final String CONNECTION_STATUS_KEY = "connection";

    public static final int WIFI_AP_STATE_ENABLED = 3;

}
